import fetch from 'dva/fetch';

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default async function request(url, options) {
  let opt = {
    method: (options && options.method) ? options.method : 'get',
    credentials: 'include',
    header: {
      'Content-Type': 'application/json;charset=utf-8'//'application:/x-www-form-urlencoded:charset=UTF-8',//'application/json;text/plan;charset=utf-8'
    },
  }
  if(options && options.body){
    opt.body = JSON.stringify(options.body)
  }
  const response = await fetch(url, opt);

  checkStatus(response);

  const data = await response.json();

  const ret = {
    data
  };
  if (response.headers.get('x-total-count')) {
    ret.headers['x-total-count'] = response.headers.get('x-total-count');
  }
  if(options && options.callback && (typeof options.callback == 'function')){
    options.callback(ret);
  } else{
    return ret;
  }
}
